import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';

import '../../widgets/base/qkd_text.dart';

class QkdCarouselView extends StatefulWidget {
  const QkdCarouselView(
      {super.key,
      required this.carousels,
      this.carouselController,
      this.needDot = true,
      this.padding,
      this.dotBottom,
      this.needTitle = true,
      this.aspectRatio,
      this.radius,
      this.tapType,
      this.autoPlay = true,
      this.tagParam});

  final List<ResourceEntity> carousels;
  final CarouselSliderController? carouselController;
  final double? padding;
  final double? dotBottom;
  final double? aspectRatio;
  final double? radius;
  final bool needDot;
  final bool needTitle;
  final String? tapType;
  final String? tagParam;
  final bool autoPlay;

  @override
  State<QkdCarouselView> createState() => _QkdCarouselViewState();
}

class _QkdCarouselViewState extends State<QkdCarouselView> {
  List<ResourceEntity> get carousels => widget.carousels;

  int page = 0;

  ResourceEntity get current => carousels[page];

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        CarouselSlider(
          carouselController: widget.carouselController,
          options: CarouselOptions(
            scrollPhysics: const ClampingScrollPhysics(),
            aspectRatio: widget.aspectRatio ?? 359 / 146,
            viewportFraction: 1,
            enableInfiniteScroll: carousels.length <= 1 ? false : true,
            autoPlay: carousels.length <= 1 ? false : widget.autoPlay,
            onPageChanged: (index, reason) {
              page = index;
              update();
            },
            onScrolled: (value) {},
          ),
          items: [
            ...List.generate(carousels.length, (i) {
              // log("${carousels.map((e) => e.toJson())}");
              final lbt = carousels[i];
              final titleEmpty = lbt.title?.trim().isEmpty ?? true;
              return GestureDetector(
                onTap: () {
                  if (widget.tapType.hasValue) {
                    Utils.onEvent(widget.tapType!,
                        params: {widget.tapType!: widget.tagParam ?? lbt.id});
                  }
                  // Get.find<UmService>().payOriginRoute = 'lbt${i + 1}';
                  lbt.doJump();
                },
                child: Container(
                  width: double.infinity,
                  height: double.infinity,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(widget.radius ?? 10)),
                  clipBehavior: Clip.hardEdge,
                  margin:
                      EdgeInsets.symmetric(horizontal: widget.padding ?? 16),
                  child: CachedNetworkImage(
                    imageUrl: carousels[i].imgUrl ?? "",
                    imageBuilder: (context, imageProvider) =>
                        makeContent(lbt, i, imageProvider, titleEmpty),
                    errorWidget: (context, url, error) =>
                        makeContent(lbt, i, null, titleEmpty),
                    placeholder: ((context, url) =>
                        makeContent(lbt, i, null, titleEmpty)),
                  ),
                ),
              );
            })
            // for (int i = 0; i < carousels.length; i++)
          ],
        ),
        if (widget.needDot)
          Positioned(
              bottom: widget.dotBottom ?? 8,
              right: 20,
              left: 8,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  ...carousels.map((e) => AnimatedContainer(
                      duration: const Duration(milliseconds: 100),
                      width: current == e ? 8 : 3,
                      height: 3,
                      margin: const EdgeInsets.symmetric(horizontal: 4),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(1.5),
                          color: current == e
                              ? Colors.white
                              : Colors.white.withAlpha(0x80))))
                ],
              ))
      ],
    );
  }

  Widget makeContent(ResourceEntity lbt, int i,
      ImageProvider<Object>? imageProvider, bool titleEmpty) {
    return Container(
      // padding: EdgeInsets.symmetric(vertical: 8, horizontal: 6),
      decoration: BoxDecoration(
        image: imageProvider != null
            ? DecorationImage(image: imageProvider, fit: BoxFit.cover)
            : null,
      ),
      child: Container(
        padding: const EdgeInsets.only(left: 12, right: 6, top: 8, bottom: 8),
        decoration: BoxDecoration(
            gradient: titleEmpty || !widget.needTitle
                ? null
                : LinearGradient(
                    colors: [
                        Colors.black.withAlpha((0xff * 0.8).toInt()),
                        Colors.black.withAlpha((0xff * 0.5).toInt()),
                        Colors.transparent,
                        Colors.transparent,
                        Colors.transparent,
                        Colors.transparent
                      ],
                    // stops: [0.2,0.5],
                    begin: Alignment.bottomCenter,
                    end: Alignment.topCenter)),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            if (widget.needTitle)
              Expanded(
                child: QkdText(
                  lbt.title ?? "",
                  color: Colors.white,
                  fontSize: 17,
                  height: 1.2,
                  maxLines: 2,
                ),
              ),
            const SizedBox(width: 4),
            // Container(
            //     decoration: BoxDecoration(
            //       borderRadius: const BorderRadius.only(
            //           topLeft: Radius.circular(4),
            //           bottomRight: Radius.circular(4)),
            //       color: Colors.black.withAlpha(0x80),
            //     ),
            //     padding: const EdgeInsets.symmetric(
            //         horizontal: 4, vertical: 0),
            //     child: Row(
            //       children: [
            //         QkdText(
            //           "${i + 1}",
            //           style: const TextStyle(
            //               color: Color(0xffdddddd),
            //               fontSize: 12),
            //         ),
            //         QkdText(
            //           "/${carousels.length}",
            //           style: const TextStyle(
            //               color: Color(0xff999999),
            //               fontSize: 12),
            //         )
            //       ],
            //     ))
          ],
        ),
      ),
    );
  }
}
